//
//  Networking.m
//  TicketingSystem
//
//  Created by Conner Wu on 15/7/20.
//  Copyright (c) 2015年 Beyondsoft. All rights reserved.
//

#import "NetworkOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFHTTPSessionManager.h"


@interface NetworkOperation ()
{
    BOOL _showError;
}

@end

@implementation NetworkOperation

- (void)dealloc
{
    NSLog(@"%s", __FUNCTION__);
}

// GET
- (void)sendDataByGet
{
    [self startRequest:HttpMethodGet];
}

// POST
- (void)sendDataByPost
{
    [self startRequest:HttpMethodPost];
}

// PUT
- (void)sendDataByPut
{
    [self startRequest:HttpMethodPut];
}

// DELETE
- (void)sendDataByDelete
{
    [self startRequest:HttpMethodDelete];
}

// send request
- (void)startRequest:(HttpMethod)method
{
    if (self.showLoading)
    {
        [[Singleton shareInstance] startLoadingInView:self.loadingSuperView];
    }
    
    
    NSString *urlString;
    urlString = [NSString stringWithFormat:@"%@%@", KwApiURL, _path];
    NSLog(@"访问地址 %@",urlString);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = (_files && _files.count > 0) ? 600 : 10;
    if (method == HttpMethodGet)
    {
#if DEBUG
        NSLog(@"\nGET 参数 %@ \n",_params);
#endif
        [manager GET:urlString parameters:_params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
            
            [self requestCompleted:operation];
            
        }
             failure:^(AFHTTPRequestOperation *operation, NSError *error)
        {
            NSLog(@"请求失败: %@", error);
            [self requestCompleted:operation];
        }];
    }
    else if (method == HttpMethodPut)
    {
#if DEBUG
        NSLog(@"\nPUT 参数%@ \n",_params);
#endif

        [manager PUT:urlString parameters:_params success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
            [self requestCompleted:operation];
        
         }
             failure:^(AFHTTPRequestOperation *operation, NSError *error)
        {
            NSLog(@"请求失败: %@", error);
            [self requestCompleted:operation];
        }];
    }
    else if (method == HttpMethodDelete)
    {
#if DEBUG
        NSLog(@" \n DELETE 参数%@ \n",_params);
#endif

        [manager DELETE:urlString parameters:_params success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            [self requestCompleted:operation];
        }
                failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
            NSLog(@"请求失败: %@", error);
            [self requestCompleted:operation];
         }];
    }
    else
    {
        NSLog(@"\nPOST 参数  %@ \n",_params);
        AFHTTPRequestOperation *operation = [manager POST:urlString parameters:_params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            // 上传文件
            if (_files && _files.count > 0)
            {
                NSLog(@"上传文件：%@", _files);
                for (NSDictionary *fileDic in _files) {
                    NSError *error;
                    NSString *filePath = [fileDic objectForKey:@"path"];
                    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
                    BOOL flag = [formData appendPartWithFileURL:fileURL name:[fileDic objectForKey:@"name"] error:&error];
                    
                    if (flag) {
                        NSLog(@"%@", error);
                    }
                }
            }
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self requestCompleted:operation];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"请求失败: %@", error);
            [self requestCompleted:operation];
        }];
        
        [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                            long long totalBytesWritten,
                                            long long totalBytesExpectedToWrite) {
            float progress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
            NSLog(@"upload: %f %f", progress, totalBytesExpectedToWrite / (1024.0 * 1024.0));
        }];
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            float progress = (float)totalBytesRead / (float)totalBytesExpectedToRead;
            NSLog(@"download: %f %f", progress, totalBytesExpectedToRead / (1024.0 * 1024.0));
        }];
    }
}

// call back
- (void)requestCompleted:(AFHTTPRequestOperation *)completedOperation
{
    [[Singleton shareInstance] stopLoading];
    
    id response = completedOperation.responseObject;
    
    NSLog(@"返回数据：%@", response ? [self DataTOjsonString:response] : completedOperation.responseString);
    
    NSLog(@"返回  状态%ld",completedOperation.response.statusCode);
    if (completedOperation.response.statusCode == 0)
    {
        //检测当前网络状态
        NSString *errorDescription = [completedOperation.error.userInfo objectForKey:@"NSLocalizedDescription"];
        if (![Network isConnect])
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"请检查您的网络" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }else
        {
            [self showMessage:errorDescription ? [errorDescription substringToIndex:errorDescription.length - 1] : @"网络异常"];
        }
    }
    else if(completedOperation.response.statusCode == 200)
    {
        NSInteger  returnCode = [[response objectForKey:kHttpReturnCodeKey] integerValue];
        if (returnCode != true)
        {
            NSString *msg = [response objectForKey:kHttpReturnMsgKey];
            [self showMessage:msg.length > 0 ? msg : @"操作失败"];
        }
    }
    else {
        if (![Network isConnect]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"网络未连接，请检查网络" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            [self showMessage:@"无法连接到服务器，请稍后再试"];
        }
    }
    
    if (self.completion)
    {
        self.completion(response);
    }
}
// show message
- (void)showMessage:(NSString *)message
{
    if (self.showError)
    {
        [SVProgressHUD showErrorWithStatus:message];
    }
}



- (NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

@end
